import React from 'react'
import PropTypes from 'prop-types'
import {
  TouchableOpacity
} from 'react-native'
import throttle from 'lodash/throttle'

export default class CustomButton extends React.PureComponent {
  static propTypes = {
    throttleTime: PropTypes.number,
    onPress: PropTypes.func,
    params: PropTypes.any,
    children: PropTypes.node,
    style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    activeOpacity: PropTypes.number
  }

  static defaultProps = {
    activeOpacity: 1
  }

  render () {
    const {
      style, children, activeOpacity
    } = this.props
    return (
      <TouchableOpacity style={style} onPress={this._onPress} activeOpacity={activeOpacity}>
        {children}
      </TouchableOpacity>
    )
  }

  _onPress = () => {
    const {
      onPress,
      params,
      throttleTime = 1000
    } = this.props
    if (onPress) {
      if (!this.handleClickThrottled) {
        this.handleClickThrottled = throttle(onPress, throttleTime, { leading: true, trailing: false })
      }
      this.handleClickThrottled(params)
    }
  }
}
